package service

import (
	"context"
	"math/big"

	"github.com/bear/wolf/config"
	"github.com/bear/wolf/utils"
	"github.com/ethereum/go-ethereum"
)

//查询合约余额
func GetContractBalance()(map[string]string,error){
	// 调用合约getbalance函数
	data, err := config.WalletABI.Pack("getbalance")
	if err != nil {
		return nil, err
	}
		// 执行合约调用
	result, err := config.EthClient.CallContract(context.Background(),
		ethereum.CallMsg{To: &config.WalletAddr, Data: data}, nil)
	if err != nil {
		return nil, err
	}
		// 解析结果
	var balance *big.Int
	if err := config.WalletABI.UnpackIntoInterface(&balance, "getbalance", result); err != nil {
		return nil, err
	}

	
	return map[string]string{
		"balance_wei": balance.String(),
		"balance_eth": utils.WeiToEth(balance),
		"contract":    config.WalletAddr.Hex(),
	}, nil
}

// TransferToContract 向合约转账（调用receive/fallback）
func TransferToContract(privKeyHex string, amountEth string) (string, error) {
	// 转换金额为wei
	amountWei := new(big.Int)
	amountWei.SetString(amountEth, 10) // 假设输入是ETH，需转换为wei（实际项目需处理1e18转换）
	amountWei.Mul(amountWei, big.NewInt(1e18))

	// 发送ETH到合约
	txHash, err := utils.SignAndSendTx(
		config.EthClient,
		privKeyHex,
		config.WalletAddr,
		amountWei,
		config.ChainID,
	)
	if err != nil {
		return "", err
	}

	return txHash, nil
}
